package vip.wangwenhao.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpCookie;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import vip.wangwenhao.common.constants.CommonConstants;
import vip.wangwenhao.common.util.UUIDUtils;

/**
 * @author wwh
 * @date 2020年01月20日 22:26
 */

@Component
public class InitFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpCookie cookie = exchange.getRequest().getCookies().getFirst(CommonConstants.UID_COOKIE_KEY);
        if (null == cookie) {
            ResponseCookie responseCookie = ResponseCookie.from(CommonConstants.UID_COOKIE_KEY, UUIDUtils.getEMUUID()).build();
            exchange.getResponse().addCookie(responseCookie);
        }
        return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().build()).build());
    }
}